<?php
class App_Module_Admin_Component_Default_Ctrl_Http extends Mozg_Controller_Instance
{

    /**
		экшен по-умолчанию
	*/
    public function PrAction ()
    {
    	$menu = $this->GetUserMenuFromCache();
		$element = current($menu);
		if ($element && isset($element['submenu']) && is_array($element['submenu']) && sizeof($element['submenu']))
		{
			$subElement = current($element['submenu']);
			$ctrlName = $subElement['link']['ctrl'];
			$actionName = $subElement['link']['action']. 'Pr';
			$this->GetCtrl($ctrlName)->$actionName();
		}
		else
		{
			if (Mozg::User()->GetId())
			{
				throw new Mozg_Exception_NotAcceptable('Access denied');
			}
			else
			{
				throw new Mozg_Exception_NotAuthorized('Not Authorized');
			}
		}
    }

    /**
		загружает основное меню админки
     */
    private function GetMenu()
    {
    	$menu = array();
		if (Mozg_Storage::Exists(Mozg_Module::GetPath($this->GetModuleName()). 'mainmenu'))
        {
            $menu = Mozg_Storage::Read(Mozg_Module::GetPath($this->GetModuleName()). 'mainmenu');
        }
         	
        return $menu;
    }
    
    private function GetUserMenu()
    {
        $user = Mozg::User();

        $groupMenu = array();
        $moduleName = $this->GetModuleName();
        $allMenu = $this->GetMenu();
        while (list ($key, $val) = each($allMenu))
        {
            $groupSubMenu = array();
            if (is_array($val['submenu']) && sizeof($val['submenu']))
            {
                while (list ($skey, $sval) = each($val['submenu']))
                {
                    if (!$user->CheckAccess($moduleName, $sval['link']['ctrl'], $sval['link']['action']))
                    {
                    	continue;
                    }
                    $groupSubMenu[$skey] = $sval;
                }
            }
            
            if (!$user->CheckAccess($moduleName, $val['link']['ctrl'], $val['link']['action']))
            {
                if (sizeof($groupSubMenu))
                {
                    reset($groupSubMenu);
                    list (, $sv) = each($groupSubMenu);
                    $val['link'] = $sv['link'];
                }
                else
                {
                    continue;
                }
            }
            
            $val['submenu'] = $groupSubMenu;
            $groupMenu[$key] = $val;
        }

        return $groupMenu;
    }
    
    protected $_groupMenu = false;
    
    public function GetUserMenuFromCache()
    {
    	if (false !== $this->_groupMenu) return $this->_groupMenu;

    	$user = Mozg::User();
        $menuFileName = Mozg_Mapper::Get('Groups')->GetCacheFileName('admin_menu', $user->GetAllGroups());
        
        if (Mozg_Storage::Exists($menuFileName) && (Mozg_Storage::ModificationTime($menuFileName) > Mozg_Mapper::Get('Groups')->GetGroupsUpdateTime($user->GetAllGroups())))
        {
        	$this->_groupMenu = Mozg_Storage::Read($menuFileName);
        }
		else
		{
			$this->_groupMenu = $this->GetUserMenu();
			Mozg_Storage::Save($menuFileName, $this->_groupMenu);
		}
			    	
        return $this->_groupMenu;
    }

    private $_reffererChecked = false;
    private $_isRightRefferer = false;
    
    /**
		проверяем, совпадает ли рефферер с URL, для предотвращения атак
	*/
    public function IsRightRefferer()
    {
		if (!$this->_reffererChecked)
		{
			$this->_reffererChecked = true;
			
			$referer = Mozg::Request('http')->getHeader('REFERER');
			$host = Mozg::Request('http')->getHeader('HOST');
			if (strlen($referer) && strlen($host))
			{
				if (preg_match('#^[^/]+\://' .preg_quote($host._ROOT_URL). '(admin|static/programs)#i', $referer))
				{
					$this->_isRightRefferer = true;
				}
			}
			else
			{
				$this->_isRightRefferer = true;
			}
		}
		
		return $this->_isRightRefferer;
    }
}